package me.firstapp.service.shop.impl;

import java.util.Date;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import me.firstapp.common.utils.Page;
import me.firstapp.module.shop.Order;
import me.firstapp.module.shop.PayRecord;
import me.firstapp.module.system.CommonSequence;
import me.firstapp.repository.shop.OrderRepository;
import me.firstapp.repository.shop.PayRecordRepository;
import me.firstapp.repository.system.CommonSequenceRepository;
import me.firstapp.service.shop.PayRecordService;

@Service
public class PayRecordServiceImpl implements PayRecordService {

	@Autowired
	private CommonSequenceRepository orderSequenceRepository;

	@Autowired
	private OrderRepository orderRepository;

	@Autowired
	private PayRecordRepository payRecordRepository;

	@Override
	public PayRecord addPayRecord(String orderNo, Double payValue, Long apiClientId) {
		PayRecord record = new PayRecord();
		Order order = orderRepository.findOrderByOrderNo(orderNo, apiClientId);
		if (order.getStatus() == 0) {
			record.setStatus(0);
		} else if (order.getStatus() == 1) {
			record.setStatus(1);
		}
		if (order.getValue() != payValue) {
			record.setStatus(2);
		}
		record.setOrderNo(orderNo);
		record.setPayTime(new Date());
		record.setPayValue(payValue);
		CommonSequence orderSequence = new CommonSequence();
		orderSequenceRepository.save(orderSequence);
		record.setPayNo(createPayRecordNo(orderNo, orderSequence.getId()));
		record.setApiClientId(apiClientId);
		payRecordRepository.save(record);
		return record;
	}

	private String createPayRecordNo(String orderNo, Long sequenceNumber) {
		return orderNo + "-" + sequenceNumber;
	}

	@Override
	public Page<PayRecord> findPayRecordPage(Integer pageNo, Integer pageSize, Map<String, Object> searchParams,
			String sortParam, String sortType, Date startTime, Date endTime, Long apiClientId) {
		return payRecordRepository.findPayRecordPage(pageNo, pageSize, searchParams, sortParam, sortType, startTime,
				endTime, apiClientId);
	}

}
